import {objectIsEq, resetLongToStr} from "@/utils/biz/common/BizUtils";
import {AndroidSDK} from "@/sdk/AndroidSdkService";
import {Observer} from "@/utils/observer/Observer";
import {UserCommitApi} from "@/api/user_common";

/**
 * 取号机 -- 交互逻辑
 */
class NumberMachineObserverBiz extends Observer {
  constructor(self, deviceInfo = {}, item) {
    super();
    // 外部组件
    this.catcheInfo = self;
    // 设备信息
    this.deviceInfo = deviceInfo;
    // 当前组件信息
    this.currentInfo = item || {};
  }

  /**
   * 消息监听入口
   * @param bizType
   * @param msgContent
   */
  async update(bizType, msgContent) {
    let self = this.catcheInfo;
    try {
      switch (bizType) {
        // 安卓调用扫码报到
        case "cardInfoCallBack":
          await this.cardInfoCallBack(msgContent);
          break;
      }
    }catch (e) {
      console.error("消息数据加载失败："+ msgContent)
      self.handleException("sdkBizServices", "安卓消息消费异常 -- "+bizType+" -- >", JSON.stringify(e.stack));
    }
  }

  /**
   * 页面自定义消息入口
   * @returns {Promise<void>}
   * @param options
   */
  async msgEvent(options = {}) {
    const {bizType, data} = options;
    switch (bizType) {
      // 取号机扫码
      case "goToInitSignBiz":
        await this.goToInitSignBiz(data);
        break;
      // 取号机扫码
      case "handleHiddenSubmit":
        await this.handleHiddenSubmit(data);
    }
  }


  /**
   * 初始化
   */
  async init() {
    await this.getAllBizAttr();
  }

  /**
   * 获取业务类型
   */
  async getAllBizAttr() {
    let self = this.catcheInfo;
    try {
      let formData = {
        terminalId: this.deviceInfo.screenId,
        terminalType: this.deviceInfo.screenType,
        businessType: this.deviceInfo.businessType,
      };
      const {code, data} = await UserCommitApi.getAllBizAttr(formData);
      if (200 === code) {
        self.bizAttrList = data || [];
        if (self.bizAttrList.length === 0) {
          await this.getBizObjList();
        } else {
          this.setBizAttrList();
        }
      }
    } catch (e) {
      self.handleException("sdkServices", "getModelDetail --> 获取模板或解析模板数据异常异常", JSON.stringify(e.stack));
    }
  }

  /**
   * 获取通用号别
   */
  async getBizObjList() {
    let self = this.catcheInfo;
    try {
      let formData = {
        terminalId: this.deviceInfo.screenId,
        terminalType: this.deviceInfo.screenType,
        businessType: this.deviceInfo.businessType,
        tenantId: this.deviceInfo.tenantId || "000000"
      };
      const {code, data} = await UserCommitApi.getBizObjList(formData);
      if (200 === code) {
        self.bizObjList = data || [];
        self.bizObjList.forEach((item) => {
          self.bizAttrList.push({
            title: item.registerObjName,
            titleShort: item.registerObjSimpleName,
            ruleType: item.ruleType,
            registerObjId: item.registerObjId,
            registerObjInfo: item,
            tackNoType: item.tackNoType
          });
        });
        this.setBizAttrList();
      }
    } catch (e) {
      self.handleException("sdkServices", "getBizObjList --> 获取号别数据异常", JSON.stringify(e.stack));
    }
  }

  /**
   * 写入下拉数据
   */
  setBizAttrList() {
    let self = this.catcheInfo;
    try {
      const formRef = self.$refs["vFormRef"];
      if (formRef) {
        formRef.executeChildMethod(this.currentInfo?.id, "reportPickInfo", self.bizAttrList);
      }
    } catch (e) {
      self.handleException("sdkBizServices", "内部组件异常 -- reportPatientInfo -- >", JSON.stringify(e.stack));
    }
  }

  /**
   * 组装扫码参数
   * @param params
   */
  getInitSignRequestParams(params) {
    let self = this.catcheInfo;
    // 扫码
    let formData = {
      terminalId: this.deviceInfo.screenId,
      terminalType: this.deviceInfo.screenType,
      businessType: this.deviceInfo.businessType,
      tenantId: this.deviceInfo.hospitalId || "000000",
      patientNo: params.patientNo,
      cardType:self.currentInitParams.cardType,
      // 患者姓名可能不存在
      patientName: params.patientName || "",
      ruleType: this.deviceInfo.ruleType || "0",
    };
    // 设置其他业务属性参数
    let bizInfo = self.currentBizInfo;
    if (bizInfo == null && self.bizAttrList.length > 0) {
      bizInfo = self.bizAttrList[0];
    }
    if (bizInfo != null) {
      // 0:临床、1:医技 、2:业务 、3:药房
      formData["ruleType"] = bizInfo.ruleType || 0;
      // 策略KEY
      formData["bizKey"] = bizInfo.bizKey;
      // 业务ID
      formData["bizId"] = bizInfo.bizId;
      // 号别ID
      if (bizInfo.registerObjInfo) {
        formData["registerObjId"] = bizInfo.registerObjInfo.registerObjId;
      }
    }
    return formData;
  }

  /**
   * 安卓调用前端扫码接口
   * 数据结构{"cardId": "","name": "","sex": "","birth": ""}
   * @param str
   * @returns {Promise<void>}
   */
  async cardInfoCallBack(str) {
    let self = this.catcheInfo;
    try {
      let obj;
      if (objectIsEq(str, "String")) {
        obj = JSON.parse(resetLongToStr(str));
      } else {
        obj = str;
      }
      let isPass = true;
      if (obj.cardId === "") {
        switch (obj.cardType + "") {
          case "8":
            let extra = obj.extra;
            if (objectIsEq(extra, "String")) {
              extra = JSON.parse(resetLongToStr(extra));
            }
            if (extra.code !== "0") {
              isPass = false;
              this.openReportResultLayer({
                title: "系统提示",
                content: extra.message,
                state: 0
              });
            }
        }
      }
      if (isPass === false) {
        return;
      }
      if (self.patientNo === obj.cardId) {
        return;
      }

      self.patientNo = obj.cardId;

      self.currentInitParams = {
        patientNo: obj.cardId,
        patientName: obj.name || "",
        cardType:obj.cardType
      }
      // 查询患者数据
      await this.initSign(self.currentInitParams);

    } catch (e) {
      AndroidSDK.writeLog("扫码报到异常 cardInfoCallBack--->" + JSON.stringify(e.stack));

      this.openReportResultLayer({
        title: "系统提示",
        content: "系统异常，请联系管理员",
        state: 0
      });
    }
  }

  /**
   * 安卓调用扫码接口
   * @param params
   * @returns {Promise<boolean>}
   */
  async initSign(params) {
    let self = this.catcheInfo;
    if(self.currentBizInfo == null){
      // 暂无任何数据时候或者接口异常提示
      this.openReportResultLayer({
        state: 0,
        title: "系统提示",
        content: "请选择要办理的业务",
        time: 5
      });
      // 当前患者信息 赋值
      self.currentPatient = params;
      self.patientNo = '';
      return false;
    }

    try {

      // 组装扫码参数
      let formData = this.getInitSignRequestParams(params);
      // 获取扫码数据
      this.openPopupLoading();
      const res = await UserCommitApi.initSign(formData);
      this.closePopupLoading();

      if (200 === res.code) {
        const {msgTips,orderNo,title,countNum} = res.data;
        this.openReportResultLayer({
          title: res.data && res.data.title ? res.data.title : "系统提示",
          content: '当前您是第' + orderNo + '号，前面等待人数' + countNum + '人 ' +  msgTips || '',
          state: 1
        });
        // 给安卓发送消息 安卓提供的能力
        AndroidSDK.takeNumberTicket({
          signId: res.data.signId,
          ruleType: res.data.ruleType,
          code: res.code
        });
      } else {
        // 接口数据异常
        this.openReportResultLayer({
          state: 0,
          title: res.data && res.data.patientName ? res.data.patientName : "系统提示",
          content: res.msg,
        });
      }
      self.currentInitParams.cardType = 0;
    } catch (e) {
      // 异常关闭弹窗再
      this.closePopupLoading();
      // 开启扫码
      this.openReadCardScan();

      AndroidSDK.writeLog("扫码报到异常 initSign--->" + JSON.stringify(e.stack));
      this.openReportResultLayer({
        title: "系统提示",
        content: "系统异常，请联系管理员",
        state: 0
      });
    } finally {
      // 重置当前选择的业务
      self.currentBizInfo = null;
      // 重置缓存数据
      self.currentPatient = null;
    }
  }



  /**
   * 取号机 扫码
   * @param item
   */
  async goToInitSignBiz(item) {
    let self = this.catcheInfo;
    // 关闭安卓读卡
    this.cancelReadCardScan();
    // 重置业务
    self.currentBizInfo = item;
    if (self.currentPatient == null && "2" === item.tackNoType) {
      // 暂无任何数据时候或者接口异常提示
      this.openReportResultLayer({
        state: 0,
        title: "系统提示",
        content: "请刷卡取号",
        time: 5
      });
      self.patientNo = '';
      return;
    }
    let formData = {
      patientNo: "",
      patientName: "",
    };
    // 设置缓存数据
    if (self.currentPatient != null && "2" === item.tackNoType) {
      formData.patientNo = self.currentPatient.patientNo || "";
      formData.patientName = self.currentPatient.patientName || "";
    }
    await this.initSign(formData);
  }

  /**
   * 银医自助一体机专用事件
   * @param data
   * @returns {Promise<void>}
   */
  async handleHiddenSubmit(data) {
    let self = this.catcheInfo;
    if (data && data.number) {
      let environment = AndroidSDK.environment;
      if (environment && 'dotnet' === environment) {
        // 判断是不是医保数据
        let number = data.number + "";
        if (number.startsWith("4243")) {
          if (self.isOpenYiBao === false) {
            // AndroidSDK.writeLog("暂未配置医保接口，如需使用医保码扫码，请联系分诊台");
            if (self.patientNo === data.number) {
              return;
            }
            self.patientNo = data.number;
            self.currentInitParams = {
              patientNo: data.number
            }
            await this.initSign(self.currentInitParams)
            return;
          }
          let formJson = {
            url: self.yiBaoInfo.url,
            orgId: self.yiBaoInfo.orgId,
            patientNo: data.number
          }
          AndroidSDK.getMedicalInsuranceData(JSON.stringify(formJson));
          // 调用C端
          return
        }
      }
      if (self.patientNo === data.number) {
        return;
      }
      self.patientNo = data.number;
      self.currentInitParams = {
        patientNo: data.number
      }
      // 调用扫码接口
      await this.initSign(self.currentInitParams)
    }
  }

  /**
   * 开启安卓的读卡器
   */
  openReadCardScan() {
    AndroidSDK.reportSDKServices("readCardNoLimit");
  }

  /**
   * 关闭安卓的读卡器
   */
  cancelReadCardScan() {
    AndroidSDK.reportSDKServices("cancelNoLimitReadCard");
  }

  /**
   * 全局消息弹窗
   * @param obj 消息对象
   */
  openReportResultLayer(obj) {
    let self = this.catcheInfo;
    self.reportResultInfo.info = Object.assign(self.reportResultInfo.info, obj);
    self.reportResultInfo.visible = true;
  }
  /**
   * 全局弹窗关闭
   */
  closeReportResultLayer() {
    let self = this.catcheInfo;
    self.reportResultInfo.visible = false;
    // 开启安卓读卡监控
    this.openReadCardScan();
  }

  /**
   * 打开loading
   */
  openPopupLoading() {
    let self = this.catcheInfo;
    self.popupLoadingInfo.visible = true;
  }

  /**
   * 关闭Loading
   */
  closePopupLoading() {
    let self = this.catcheInfo;
    self.popupLoadingInfo.visible = false;
  }

}

export {NumberMachineObserverBiz};
